import { defineStore } from 'pinia';
import {
	login as userLogin,
	logout as userLogout,
	getUserInfo,
	LoginData,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
	state: () : UserState => ({
		status: undefined,
		createTime: undefined,
		number: undefined,
		username: undefined,
		avatarUrl: undefined,
		salt: undefined,
		wxUnion: undefined,
		roleCode: undefined,
		roleName: undefined,
		menuList: undefined
	}),

	getters: {
		userInfo(state : UserState) : UserState {
			return { ...state };
		},
	},

	actions: {
		
		setInfo(partial : Partial<UserState>) {
			this.$patch(partial);
		},

		// Reset user's information
		resetInfo() {
			this.$reset();
		},

		// Get user's information
		async info() {
			const res = await getUserInfo();
			this.setInfo(res.data);
		},

		// Login
		async login(_loginForm : LoginData) {
			try {
				const res = await userLogin(_loginForm);
				setToken(res.data.access_token);
			} catch (err) {
				clearToken();
				throw err;
			}
		},
		logoutCallBack() {
			const appStore = useAppStore();
			this.resetInfo();
			clearToken();
			removeRouteListener();
			appStore.clearServerMenu();
		},
		// Logout
		async logout() {
			try {
				await userLogout();
			} finally {
				this.logoutCallBack();
			}
		},
	},
});

export default useUserStore;